import useDebounce from "../useDebounce"
import { Select, SelectProps } from "antd"
import { useCallback, useEffect, useState } from "react"
interface ProSelectProps extends SelectProps {
  dep?: any
  request?: any
  data?: any
  searchName?: string
  searchValue?: string
  formatResult?: (res) => any
}

const ProSelect = ({ dep,searchValue, request, searchName, formatResult, data,  ...rest }: ProSelectProps) => {
  const [options, setOptions] = useState([])
  const query = (queryParams: any) => {
    request({ ...data, ...queryParams }).then(res => {
      let _options = [];
      if (formatResult) {
        _options = formatResult(res);
      }
      else if (Array.isArray(res)) {
        _options = res
      } else if (Array.isArray(res.data)) {
        _options = res.data
      } else {

      }
      setOptions([..._options])
      // setOptions(_options.map(item => {
      //   const valueKey = fieldNames ? fieldNames.value : 'value'
      //   const labelKey = fieldNames ? fieldNames.label : 'label'
      //   return {
      //     value: item[valueKey],
      //     label: item[labelKey]
      //   }
      // }))
      // console.log({res})
    })
  }

  const onSearch = useDebounce((value) => {
    if(searchName){
      console.log(value,searchName)
      query({
        [searchName]: value
      })
    }
    
  }, 200)
  useEffect(() => {
    if(searchName){
      query({
        [searchName]:searchValue
      })
    }else{
      query({})
    }
   
  }, [dep])
  // const onSearch = (value) => {
  //   if (searchName) {
  //     query({
  //       [searchName]: value
  //     })
  //   }
  // }
console.log('restrest',rest)
  return <Select filterOption={!searchName} onSearch={onSearch} style={{ minWidth: 200 }} options={options} {...rest} />
}
export default ProSelect